//
//  UserPayload.swift
//  hello
//
//  Created by yafei li on 2025/9/18.
//
import Vapor
import JWT

struct UserPayload: Content,Authenticatable, JWTPayload {
    let id: UUID
    let name: String
    let phone: String
    let exp: ExpirationClaim
 
    func verify(using algorithm: some JWTAlgorithm) async throws {
        do {
            try self.exp.verifyNotExpired()
        } catch  {
            throw Abort.tokenInvalid
        }
    }
}


extension UserPayload {
    //    从请求的JWT令牌中获取当前用户
    static func getCurrentUserFromToken(req: Request) async throws -> User {
        let payload = try await req.jwt.verify(as: UserPayload.self)
        guard let userId = UUID(uuidString:  payload.id.uuidString) else { throw Abort.tokenInvalid }
        guard let user = try await User.find(userId, on: req.db) else {
            throw Abort.userNotExist
        }
        return user
    }
}
